import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import compression from 'vite-plugin-compression'
import progress from 'vite-plugin-progress'
import { ViteImageOptimizer } from 'vite-plugin-image-optimizer'
// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    // 自动引入
    AutoImport({
      resolvers: [ElementPlusResolver()],
      // 其他模块自动导入配置
      imports: ['vue', 'vue-router', 'pinia'],
      dts: 'types/auto-imports.d.ts',
    }),
    Components({
      resolvers: [ElementPlusResolver()],
      dts: 'types/components.d.ts',
    }),
    //  gzip压缩
    compression({
      ext: '.gz',
      algorithm: 'gzip',
      threshold: 10240, // 仅压缩大于10kb的文件
      deleteOriginFile: false, // 是否删除原始文件
    }),
    // 打包进度
    progress(),
    // 图片压缩
    ViteImageOptimizer(),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "@/styles/variables.scss" as *;`,
      },
    },
  },
  server: {
    port: 8080,
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
  },
  build: {
    assetsInlineLimit: 4096, // 4kb 以下的资源会自动转成 base64
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('node_modules')) {
            if (id.includes('vue')) return 'vue'
            return 'vendor'
          }
        },
      },
    },
  },
})
